/*
 * Copyright 2010 Christoph Widulle (christoph.widulle@googlemail.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the
 * License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS"
 * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */


package com.android1.amarena2d.input;

import com.android1.amarena2d.nodes.behavior.HasXY;


/**
 * Will update the given position to the coordinates that have been touched
 */
public class DragController implements TouchListener {

    boolean exclusive = true;

    HasXY position;

    boolean hit;
    int activePointer = -1;

    public DragController(final HasXY position) {
        this.position = position;
    }

    protected void updatePos(float x, float y) {
        position.setXY(x, y);
    }

    public boolean isExclusive() {
        return exclusive;
    }

    /**
     * If true, will consume the event and no other touchlistener will be notified.
     * Set to false, if you want to have more draggable layers for example.
     *
     * @param exclusive
     * @return
     */
    public DragController setExclusive(final boolean exclusive) {
        this.exclusive = exclusive;
        return this;
    }

    @Override
    public boolean onTouchDown(float x, float y, int pointer, boolean isHit) {
        if (!isHit || (this.activePointer != -1 && this.activePointer != pointer))
            return false;

        updatePos(x, y);
        this.hit = true;
        this.activePointer = pointer;
        return exclusive;
    }

    @Override
    public boolean onTouchUp(float x, float y, int pointer, boolean isHit) {
        if (this.activePointer != -1 && this.activePointer != pointer)
            return false;
        this.activePointer = -1;
        hit = false;
        return exclusive;
    }

    @Override
    public boolean onTouchDragged(float x, float y, int pointer, boolean isHit) {
        if (!hit || (this.activePointer != -1 && this.activePointer != pointer))
            return false;
        updatePos(x, y);
        return exclusive;

    }
}
